public with sharing class ctrl_PackageSelection 
{
	//For Variables...
    public Boolean refreshPage {get;set;}
    public Boolean cancelFlag {get;set;}
	public string accountID {get;set;}
	public string amendmentID {get;set;}
	public string isPerformaInvoice {get;set;}
	public string recordTypeName {get;set;}
	public string tenancyID {get;set;}
	public string activityType {get;set;}
	public string accountExpiryDate {get;set;}
	public string licenseApplicationType {get;set;}
	List<Payment_Plan__c> paymentPlanList = new List<Payment_Plan__c>();
	Map<string,Payment_Plan__c> paymentPlanMap = new Map<string,Payment_Plan__c>();
	
	public Set<string> locationTypeSet {get;set;}
	List<Id> paymentPlanIDList = new List<Id>();
	
	Map<string,string> locationTypeMap = new Map<string,string>();
	public Map<string,string> installmentSelectionMap {get;set;}
	public Map<string,string> installmentSelectionDescriptionMap {get;set;}
	
	public Map<string,List<SelectOption>> installmentPlanMap{get;set;}
	
	
	List<Amendment__c> amendmentObjectList = new List<Amendment__c>();
	List<Tenancy_Contract__c> tenacnyObjectList = new List<Tenancy_Contract__c>();
	
	
	public List<string> resultList {get;set;}
	
	//For Contructors...
    public ctrl_PackageSelection(ApexPages.StandardController controller) 
    {
    	refreshPage = false;
    	cancelFlag = false;
    	accountID = null;
    	tenancyID = null;
    	amendmentID = null;
    	isPerformaInvoice = null;
    	licenseApplicationType = null;	
    	locationTypeSet  = new set<string>();
    	installmentSelectionMap = new Map<string,string>();
    	installmentSelectionDescriptionMap = new Map<string,string>();
    	installmentPlanMap = new Map<string,List<SelectOption>>();
    	resultList = new List<string>();
    	
    	if(ApexPages.CurrentPage().getParameters().get('accountID') != null)
    		accountID = ApexPages.CurrentPage().getParameters().get('accountID');
    	if(ApexPages.CurrentPage().getParameters().get('amendmentID') != null)
    		amendmentID = ApexPages.CurrentPage().getParameters().get('amendmentID');	
        if(ApexPages.CurrentPage().getParameters().get('tenancyID') != null)
    		tenancyID = ApexPages.CurrentPage().getParameters().get('tenancyID');
    	if(ApexPages.CurrentPage().getParameters().get('licenseType') != null)	
	    	licenseApplicationType = ApexPages.CurrentPage().getParameters().get('licenseType');
	    if(ApexPages.CurrentPage().getParameters().get('isPerformaInvoice') != null)	
	    	isPerformaInvoice = ApexPages.CurrentPage().getParameters().get('isPerformaInvoice');
    	
    	System.debug('The isPerforma Invoice Value in Package Selection => '+ isPerformaInvoice);
    
    }

	//Method for Loading all the Current Records...
	public PageReference loadingPaymentPlanMethod()
	{
		try
		{
			//First Getting all the location type...
			//if(tenancyID != null &&  licenseApplicationType == 'Tenancy')
			if(tenancyID != null &&  licenseApplicationType == 'Renewal')
			{
				for(Tenancy_Contract__c tenancyObject : [select id,Tenant__c,Account_Activity__c,Account_Expiry_Date__c,Location_type__c, Tenancy_Contract_Cancellation_Date__c FROM Tenancy_Contract__c where Tenancy_Contract_Cancellation_Date__c =: null AND Id =: tenancyID ])	
				{
					locationTypeMap.put(tenancyObject.Location_type__c,tenancyObject.Location_type__c);
					
					//Adding in the list...
					tenacnyObjectList.add(tenancyObject);
				}
			}
			else if (amendmentID != null && licenseApplicationType == 'Amendment')
			{
			
				for(Amendment__c amendmentObject : [select Account__c,Account_Legal_Status__c,Record_Type_Name__c,New_Location_Type_1__c,New_Location_Type_2__c,New_Location_Type_3__c,Account_License__c,New_License_Type__c,Total_Share_Holders__c,NTCDI__c,OTCDL__c,Company_Capital__c,New_Location_1_Name__c,New_Location_2_Name__c,New_Location_3_Name__c,New_Location__c,New_Location_2__c,New_Location_3__c,NLPPD_3__c,NLPPD_2__c,NLPPD__c,PTCPPD__c,Id,Keys_Required__c,Amendment_Application_Status__c from Amendment__c where Id =:amendmentId])
	        	{
	        		if(amendmentObject.New_Location_Type_1__c != null)
	        			locationTypeMap.put(amendmentObject.New_Location_Type_1__c,amendmentObject.New_Location_Type_1__c);	
	        		if(amendmentObject.New_Location_Type_2__c != null)
	        			locationTypeMap.put(amendmentObject.New_Location_Type_2__c,amendmentObject.New_Location_Type_2__c);
	        		if(amendmentObject.New_Location_Type_3__c != null)
	        			locationTypeMap.put(amendmentObject.New_Location_Type_3__c,amendmentObject.New_Location_Type_3__c);	
	        			 					
	        		//Adding in the List...	 					
	        		amendmentObjectList.add(amendmentObject);
	        		
	        	}
	        	
			}
			else if(accountID != null && licenseApplicationType == 'New License')
			{
				for(Location_Booking_Information__c locationObject : [Select Location__r.Name,Location__r.Location_Type__c,Location__r.Rental_Rate__c,Location__r.Fee__r.Name, Location__r.Fee__r.Fee_Type__c, Location__r.Id, Location__c, License_Booking_Status__c, Id, Booking_Released_Date__c, Booking_Leasing_Issue_Date__c, Booking_Date__c, Account__c From Location_Booking_Information__c where Account__c =: accountId AND License_Booking_Status__c = 'Booked'])	
				{
					locationTypeMap.put(locationObject.Location__r.Location_Type__c,locationObject.Location__r.Location_Type__c);
				}
			}	
			
			else if(accountID != null && licenseApplicationType == 'Renewal')
			{
				for(Tenancy_Contract__c tenancyObject : [select id,Location_type__c, Tenancy_Contract_Cancellation_Date__c FROM Tenancy_Contract__c where Tenancy_Contract_Cancellation_Date__c =: null AND Tenant__c =: accountID])	
				{
					locationTypeMap.put(tenancyObject.Location_type__c,tenancyObject.Location_type__c);
				}	
			
			}
			
			else if(accountID != null && (licenseApplicationType == 'Renewal Amendment'))
			{
				for(Account_Location__c accountLocationObject : [Select New_Location__r.Rental_Rate__c,New_Location__r.Location_Type__c,Account_Expiry_Date__c,renewAddLocationFlag__c,Previous_Tenancy_Contract__r.Location__r.Location_Type__c,Previous_Tenancy_Contract__r.Account_Today_Expiry_Date__c,Previous_Tenancy_Contract__r.Location__r.Rental_Rate__c,Previous_Tenancy_Contract__r.Account_Expiry_Date__c,isRenewed__c, Previous_Tenancy_Contract__r.Fine_Per_Day__c, Previous_Tenancy_Contract__r.Tenancy_Contract_Cancellation_Date__c, Previous_Tenancy_Contract__r.Location_type__c, Previous_Tenancy_Contract__r.Rental_Rate__c, Previous_Tenancy_Contract__r.Tenancy_Contract_Expiry_Date__c, Previous_Tenancy_Contract__r.Tenancy_Contract_Start_Date__c, Previous_Tenancy_Contract__r.Tenant__c, Previous_Tenancy_Contract__r.Location__c, Previous_Tenancy_Contract__r.Location__r.Current_Tenancy_Contract__c, Previous_Tenancy_Contract__r.Id, Previous_Tenancy_Contract__c, Previous_Location__c, New_Location__c, Name, Id, Flag__c, Edit_Flag__c, Delete_Flag__c, Add_Flag__c, Account__c From Account_Location__c where Account__c =: accountID AND Delete_Flag__c =: false AND isRenewed__c =: false])	
				{
					if(accountLocationObject.renewAddLocationFlag__c != true && accountLocationObject.New_Location__c != null)
						locationTypeMap.put(accountLocationObject.New_Location__r.Location_Type__c,accountLocationObject.New_Location__r.Location_Type__c);
					else if(accountLocationObject.Previous_Tenancy_Contract__r.Location__r.Current_Tenancy_Contract__c != null && accountLocationObject.Previous_Tenancy_Contract__c == accountLocationObject.Previous_Tenancy_Contract__r.Location__r.Current_Tenancy_Contract__c)
                    	locationTypeMap.put(accountLocationObject.Previous_Tenancy_Contract__r.Location__r.Location_Type__c,accountLocationObject.Previous_Tenancy_Contract__r.Location__r.Location_Type__c);
				
				}
			}	
			
			//Location Type Map...
			if(locationTypeMap.size() > 0)
			{
				for(Payment_Plan__c paymentObject : [Select isActive__c, Sign_Multiplier__c,Percent__c, Location_Type__c, Installment__c, Id, Action__c From Payment_Plan__c WHERE isActive__c =: true AND License_Application_Type__c =: licenseApplicationType  AND Location_Type__c IN : locationTypeMap.KeySet()])	
				{
					
					//Adding in the Set...
					locationTypeSet.add(paymentObject.Location_Type__c);
					
					//Adding in the Payment Plan Map...
					paymentPlanMap.put(paymentObject.Location_Type__c + '::'+ paymentObject.Installment__c, paymentObject);
					
					//For Display Purpose...
					installmentSelectionMap.put(paymentObject.Location_Type__c, '1');
					
					if(paymentPlanMap.get(paymentObject.Location_Type__c+'::1') != null)
					{
						string tempString = paymentPlanMap.get(paymentObject.Location_Type__c+'::1').Percent__c + ' % ' + paymentPlanMap.get(paymentObject.Location_Type__c+'::1').Action__c;
						installmentSelectionDescriptionMap.put(paymentObject.Location_Type__c, tempString);	
					}
					
				}		
					
					
				System.debug('The Size => '+ locationTypeSet.size());	
			}
				
			//Returning the values...
			return null;
		}
		catch(Exception exp)
		{
			System.debug('The Error : Line Number : ' + exp.getLineNumber() + ' & the Message : '+ exp.getMessage());
			ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, exp.getMessage());
            ApexPages.addMessage(msg);
            
			//return exp.getMessage();
			return null;
		}
		
		//Returning the Values...
		return null;
		
	}
	
	
	//Button for the Generate Invoice...
	public PageReference generateInvoiceMethod()
	{
		paymentPlanList = new List<Payment_Plan__c>();
		resultList = new List<string>();
		
		try
		{
			
			if(isPerformaInvoice != null)
				isPerformaInvoice = 'True';
			else
				isPerformaInvoice = 'False';	
			
			System.debug('The isPerforma Invoice Value => ' + isPerformaInvoice);
			if(installmentSelectionMap.size() > 0)
			{
			
				for(string locationType : installmentSelectionMap.keyset())
				{
					System.debug('The Location Type : '+ locationType);
					System.debug('The Installment Plan : '+ installmentSelectionMap.get(locationType));
					
					if(installmentSelectionMap.get(locationType) != null && paymentPlanMap.get(locationType+'::'+installmentSelectionMap.get(locationType)) != null)
					{
						/*string tempString = paymentPlanMap.get(locationType+'::'+installmentSelectionMap.get(locationType)).Percent__c + ' % ' + paymentPlanMap.get(locationType+'::'+installmentSelectionMap.get(locationType)).Action__c;
						installmentSelectionDescriptionMap.put(locationType, tempString);
					 	*/
					 	
					 	//Adding Payment Plan Object in the List...
						paymentPlanList.add(paymentPlanMap.get(locationType+'::'+installmentSelectionMap.get(locationType)));
							
					}
				}	
				
				//Now Calling Invoie Methods...	
				if(paymentPlanList.size() > 0)
				{
		
					//For New License or Renewal and Renewal Amendment...
					if(accountID != null && (licenseApplicationType == 'New License' || licenseApplicationType == 'Renewal' || licenseApplicationType == 'Renewal Amendment' ))
					{
						List<Account> accountObject = new List<Account>([SELECT Id,Record_Type_Name__c,Activity__c,License_Expiry_Date__c,Renew_Additional_Type__c,License_Application_Type__c from Account WHERE ID =: accountID]); 
						
						if(accountObject.size()> 0)
						{
							
							if(licenseApplicationType == 'New License')
							{
								System.debug('The Performa Invoice => '+ isPerformaInvoice);
								resultList = issueRecieptAndInvoiceClass.generatingInvoiceAndLineItemForNewLicenseMethod(accountObject[0].Id, accountObject[0].License_Application_Type__c, accountObject[0].Activity__c,isPerformaInvoice,paymentPlanList);
								System.debug('The Total Result Size in New License '+ resultList.size());
								
							}
							else if (licenseApplicationType == 'Renewal')
							{
								string popDate  = string.valueof(accountObject[0].License_Expiry_Date__c); 
						        System.debug('The Before POP Date => '+ popDate);
						        popDate = string.valueOf(popDate.split('-')[2]+'/'+popDate.split('-')[1]+'/'+popDate.split('-')[0]);
								//resultList = issueRecieptAndInvoiceClass.generatingInvoiceAndLineItemForRenewalLicenseMethod(accountObject[0].Id, accountObject[0].License_Application_Type__c, accountObject[0].Activity__c, string.valueof(accountObject[0].License_Expiry_Date__c),isPerformaInvoice,paymentPlanList);
								resultList = issueRecieptAndInvoiceClass.generatingInvoiceAndLineItemForRenewalLicenseMethod(accountObject[0].Id, accountObject[0].License_Application_Type__c, accountObject[0].Activity__c, popDate,isPerformaInvoice,paymentPlanList);
							}
							else if (licenseApplicationType == 'Renewal Amendment')
							{
								string popDate  = string.valueof(accountObject[0].License_Expiry_Date__c); 
						        System.debug('The Before POP Date => '+ popDate);
						        popDate = string.valueOf(popDate.split('-')[2]+'/'+popDate.split('-')[1]+'/'+popDate.split('-')[0]);
						        
								//resultList = issueRecieptAndInvoiceClass.generatingInvoiceAndLineItemForRenewalLicenseAdditionalMethod(accountObject[0].Id, accountObject[0].License_Application_Type__c, accountObject[0].Activity__c, string.valueof(accountObject[0].License_Expiry_Date__c), accountObject[0].Renew_Additional_Type__c,isPerformaInvoice,paymentPlanList);	
								resultList = issueRecieptAndInvoiceClass.generatingInvoiceAndLineItemForRenewalLicenseAdditionalMethod(accountObject[0].Id, accountObject[0].License_Application_Type__c, accountObject[0].Activity__c, popDate, accountObject[0].Renew_Additional_Type__c,isPerformaInvoice,paymentPlanList);
							}
							
						}
						
					}
					else if (amendmentID != null && licenseApplicationType == 'Amendment')
					{
						if(amendmentObjectList.size() > 0)
						{
							resultList = issueRecieptAndInvoiceClass.generatingAmendmentInvoiceAndLineItemForAmendmentMethod(amendmentObjectList[0].Account__c, amendmentObjectList[0].Id, amendmentObjectList[0].Record_Type_Name__c, amendmentObjectList[0].Account_Legal_Status__c,isPerformaInvoice,paymentPlanList);
						}
						
					}
					//else if(tenancyID != null &&  licenseApplicationType == 'Tenancy')
					else if(tenancyID != null &&  licenseApplicationType == 'Renewal')
					{
						if(tenacnyObjectList.size() > 0)
						{
							string popDate  = string.valueof(tenacnyObjectList[0].Account_Expiry_Date__c); 
					        System.debug('The Before POP Date => '+ popDate);
					        popDate = string.valueOf(popDate.split('-')[2]+'/'+popDate.split('-')[1]+'/'+popDate.split('-')[0]);
					        
							//resultList = issueRecieptAndInvoiceClass.generatingInvoiceAndLineItemForRenewalLicenseForTenancyContractMethod(tenacnyObjectList[0].Tenant__c, tenacnyObjectList[0].Id, string.valueof(tenacnyObjectList[0].Account_Expiry_Date__c), tenacnyObjectList[0].Account_Activity__c,isPerformaInvoice,paymentPlanList);	
							resultList = issueRecieptAndInvoiceClass.generatingInvoiceAndLineItemForRenewalLicenseForTenancyContractMethod(tenacnyObjectList[0].Tenant__c, tenacnyObjectList[0].Id, popDate, tenacnyObjectList[0].Account_Activity__c,isPerformaInvoice,paymentPlanList);
						
						}
						
					}
					System.debug('The Size of Result => '+ resultList.size());
					//For Result...
					if(resultList.size() > 0)
						refreshPage = true;
					else
					{
						ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.Error, 'Some Unexpected Error encountered during genrating Invoices !!!');
			            ApexPages.addMessage(msg);
			            return null;
						
					}
					
					System.debug('The Refresh Page => '+ refreshPage);
					
							
				}
				else
				{
					System.debug('There is no Payment Plan Available for these Location Type');
					ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'There is no Installment Plan Available for these Location Type');
		            ApexPages.addMessage(msg);
		            return null;
					
				}			
				
			}
			else
			{
				System.debug('There is no Installment Plan Available for these Location Type');
				ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'There is no Installment Plan Available for these Location Type');
	            ApexPages.addMessage(msg);
	            return null;
				
			}
			
			//Return the values...
			return null;	
		}
		catch(Exception exp)
		{
			System.debug('The Error : Line Number : ' + exp.getLineNumber() + ' & the Message : '+ exp.getMessage());
			ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.Error, exp.getMessage());
            ApexPages.addMessage(msg);
            
			//return exp.getMessage();
			return null;
		}
		
		
		
		
		
	}
	
	//For Cancel Button...
	public PageReference cancelButton()
	{
		cancelFlag = true;
		
		return null;
	}


	//For Display Description...
	public PageReference displayMessagePanel()
	{
		try
		{
			System.debug('Calling Display Message Panel');
	
			for(string locationType : installmentSelectionMap.keyset())
			{
				System.debug('The Location Type : '+ locationType);
				System.debug('The Installment Plan : '+ installmentSelectionMap.get(locationType));
				
				if(installmentSelectionMap.get(locationType) != null && paymentPlanMap.get(locationType+'::'+installmentSelectionMap.get(locationType)) != null)
				{
					string tempString = paymentPlanMap.get(locationType+'::'+installmentSelectionMap.get(locationType)).Percent__c + ' % ' + paymentPlanMap.get(locationType+'::'+installmentSelectionMap.get(locationType)).Action__c;
					installmentSelectionDescriptionMap.put(locationType, tempString);
				
					System.debug('The Temp String : '+ tempString);	
				}
				
				
				
			}
			
			//returning the values...
			return null;	
		}
		catch(Exception exp)
		{
			System.debug('The Error : Line Number : ' + exp.getLineNumber() + ' & the Message : '+ exp.getMessage());
			ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.Error, exp.getMessage());
            ApexPages.addMessage(msg);
            
			//return exp.getMessage();
			return null;
		}
			
	}

	//For Properties...
	public Map<string,List<SelectOption>> getInstallment()
	{
		try
		{
			//Installment Plan...
			//installmentPlanMap = new Map<string,List<SelectOption>>();
			
			for(String locationType : locationTypeMap.keyset())
			{
				
				//List Option...
				List<SelectOption> options = new List<SelectOption>();
		        options.add(new SelectOption('1','1'));
		        options.add(new SelectOption('2','2'));
		        options.add(new SelectOption('3','3'));
		        options.add(new SelectOption('4','4'));
		        options.add(new SelectOption('5','5'));
		        options.add(new SelectOption('6','6'));
		        options.add(new SelectOption('7','7'));
		        options.add(new SelectOption('8','8'));
		        options.add(new SelectOption('9','9'));
		        options.add(new SelectOption('10','10'));
		        options.add(new SelectOption('11','11'));
		        options.add(new SelectOption('12','12'));
		        
		        
		        //Adding in the map...
		        installmentPlanMap.put(locationType, options);
				
				/*installmentSelectionMap.put(locationType, '1');
				string tempString = paymentPlanMap.get(locationType+'::1').Percent__c + ' % ' + paymentPlanMap.get(locationType+'::1').Action__c;
				installmentSelectionDescriptionMap.put(locationType, tempString);*/
					
			
			}
			
	        return installmentPlanMap;
		}
		catch(Exception exp)
		{
			System.debug('The Error : ' + exp.getLineNumber() + ' Message : '+ exp.getMessage());
			ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO,'The Error : ' + exp.getLineNumber() + ' Message : '+ exp.getMessage());
            ApexPages.addMessage(msg);
            return null;
		}
	}
}